package com.qmx.launcher.bean;

import android.util.Log;


import com.qmx.launcher.constant.AppConstant;
import com.qmx.launcher.constant.EventConfig;
import com.qmx.launcher.event.BoardEvent;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.net.Socket;

/**
 * @author chengxiangtong
 * @date 2018/12/15
 * version : 1.0
 * class describe：*
 */
public class DrawBoardAction extends Thread {
    private static final String TAG = DrawBoardAction.class.getSimpleName();
    private static DrawBoardClient client;
    private String ip;
    private int port = 0;

    public DrawBoardAction(String ip, int port) {
        this.port = port;
        this.ip = ip;
    }

    public DrawBoardAction(String ip) {
        this.ip = ip;
    }

    private void initSocket() {
        try {
            Socket socket;
            if (port == 0) {
                socket = new Socket(ip, AppConstant.PORT);
            } else {
                socket = new Socket(ip, port);
            }
            client = new DrawBoardClient(socket);

        } catch (IOException e) {
            e.printStackTrace();
            close();
        }
    }

    @Override
    public void run() {
        initSocket();
        if (client != null) {
            while (!client.isClosed())
                try {
                    DrawBoardData dtpg = (DrawBoardData) client.receive();
                    Object data = dtpg.getData();
                    switch (dtpg.getType()) {
                        case POINT:
                            EventBus.getDefault().post(new BoardEvent(EventConfig.POINT, data));
                            break;
                        case COMMAND:
                            EventBus.getDefault().post(new BoardEvent(EventConfig.COMMAND, data));
                            break;
                        case COLOR:
                            EventBus.getDefault().post(new BoardEvent(EventConfig.COLOR, data));
                            break;
                        case STROKE:
                            EventBus.getDefault().post(new BoardEvent(EventConfig.STROKE, data));
                            break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    close();
                }
        }
    }

    public static void sendData(DrawBoardData.DataType type, Object data) {
        DrawBoardData dp = new DrawBoardData(type, data);
        sendDataPackage(dp);
    }

    public static void sendDataPackage(DrawBoardData dp) {
        if (client != null && !client.isClosed()) {
            try {
                client.send(dp);
            } catch (Exception e) {
                close();
            }
        }
    }

    public static void close() {
        if (client != null) {
            client.close();
            Log.e(TAG, "client close");
        }
    }
}
